﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Data;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using PluginCommon;
using WinAPI.User32;

namespace FileSearcher
{
    public partial class MainUserControl : PluginFormBase
    {
        public MainUserControl()
        {
            InitializeComponent();
        }

        private void ClearButton_Click(object sender, EventArgs e)
        {
            ResultListBox.Items.Clear();
        }

        private void SearchButton_Click(object sender, EventArgs e)
        {
            folderBrowserDialog1.ShowDialog(this);
            string folder = folderBrowserDialog1.SelectedPath;

            string[] sqlFiles = Directory.GetFiles(folder, patternTextBox.Text.Trim(), SearchOption.AllDirectories);
            this.Cursor = Cursors.WaitCursor;
            foreach (string file in sqlFiles)
            {
                var streamReader = new StreamReader(file);
                string content = streamReader.ReadToEnd();
                streamReader.Close();

                if (content.IndexOf(KeyWordTextBox.Text.Trim(), StringComparison.CurrentCultureIgnoreCase) > -1)
                    ResultListBox.Items.Add(file);
            }
            this.Cursor = Cursors.Arrow;
        }

        private void ResultListBox_DoubleClick(object sender, EventArgs e)
        {
            if (UseNotePadCheckBox.Checked)
            {
                Process.Start("notepad.exe", ResultListBox.SelectedItem.ToString());
            }
            else
            {
                var shellExecuteInfo = new ShellExecuteInfo
                                           {
                                               lpVerb = Marshal.StringToHGlobalAuto("open"),
                                               lpFile =
                                                   Marshal.StringToHGlobalAuto(ResultListBox.SelectedItem.ToString())
                                           };
                User32Dll.ShellExecuteEx(shellExecuteInfo);
            }
        }
    }
}
